import Vue from 'vue'

// 设置相机配置
let setOptions = (srcType) => {
  let options = {
    // Some common settings are 20, 50, and 100
    quality: 100,
    destinationType: window.Camera.DestinationType.FILE_URI,
    // In this app, dynamically set the picture source, Camera or photo gallery
    sourceType: srcType,
    encodingType: window.Camera.EncodingType.JPEG,
    mediaType: window.Camera.MediaType.PICTURE,
    allowEdit: false,
    correctOrientation: true  // Corrects Android orientation quirks
  }
  return options
}

// 有获取有效的FileEntry对象
/* eslint-disable */
let getFileEntry = (imageUrl) => {
  return new Promise((resolve, reject) => {
    window.resolveLocalFileSystemURL(imageUrl, (fileEntry) => {
      resolve(fileEntry)
    }, () => {
      window.resolveLocalFileSystemURL(window.cordova.file.cacheDirectory, (dirEntry) => {
        dirEntry.getFile(`tempImage.jpeg`, { create: true, exclusive: false }, (fileEntry) => {
          resolve(fileEntry)
        }, error => {
          reject(error)
        })
      }, error => {
        reject(error)
      })
    })
  })
}

// 多张图片上传
let multipleUpload = (uploadUrl, medias = [], params) => {
  const promiseForEach = (arr, cb) => {
    let realResult = []
    let result = Promise.resolve()
    arr.forEach((a, index) => {
      result = result.then(() => {
        return cb(a).then((res) => {
          realResult.push(res)
        })
      })
    })
    return result.then(() => {
      return realResult
    })
  }
  return promiseForEach(medias, (item) => {
    return new Promise((resolve, reject) => {
      item.quality = 100
      MediaPicker.compressImage(item, (compressData) => {
        let path = compressData.path
        if (path.indexOf('file://') == -1) {
          path = 'file://' + path
        }
        startUpload(uploadUrl, path, params).then(data => {
          let url = data.data[0]
          return resolve(url)
        }).catch(e => {
          return reject(e)
        })
      })
    })
  })
}

// 开始上传
/* eslint-disable */
let startUpload = (uploadUrl, imageUrl, params = {}) => {
  return new Promise((resolve, reject) => {
    getFileEntry(imageUrl).then(fileEntry => {
      let ft = new FileTransfer()
      let fileURL = fileEntry.toURL()
      let options = new FileUploadOptions()
      options.fileKey = 'file'
      options.fileName = 'image.jpg'
      options.httpMethod = 'POST'
      options.mimeType = 'image/jpeg'
      options.params = params
      Vue.$vux.loading.show({
        text: '正在上传，请稍等...'
      })
      ft.upload(fileURL, encodeURI(uploadUrl), (data) => {
        let result = JSON.parse(data.response)
        Vue.$vux.loading.hide()
        resolve(result)
      }, (error) => {
        Vue.$vux.loading.hide()
        reject(error)
      }, options)
    })
  })
}

const upload = {

  /**
   * 多张图片上传
   */
  multipleUpload: multipleUpload,

  /**
   * 开始上传
   */
  startUpload: startUpload,

  /**
   * 从媒体库中获取图片
   */
  chooseAlbum1 (maxSelectCount = 1) {
    return new Promise((resolve, reject) => {
      let args = {
        'selectMode': 100, //101=picker image and video , 100=image , 102=video
        'maxSelectCount': maxSelectCount, //default 40 (Optional)
        'maxSelectSize': 188743680, //188743680=180M (Optional)
      };
      MediaPicker.getMedias(args, (medias) => {
        resolve(medias)
      }, (e) => {
        reject(e)
      })
    })
  },

  /**
   * 从媒体库中获取图片
   */
  chooseAlbum () {
    return new Promise((resolve, reject) => {
      let srcType = window.Camera.PictureSourceType.PHOTOLIBRARY
      let options = setOptions(srcType)
      navigator.camera.getPicture((imageUrl) => {
        resolve(imageUrl)
      }, (error) => {
        reject(error)
        console.debug(`Unable to obtain picture: ${error} app`)
      }, options)
    })
  },

  /**
   * 拍照图片上传
   */
  takePhoto () {
    return new Promise((resolve, reject) => {
      let srcType = window.Camera.PictureSourceType.CAMERA
      let options = setOptions(srcType)
      navigator.camera.getPicture((imageUrl) => {
        resolve(imageUrl)
      }, (error) => {
        reject(error)
        console.debug(`Unable to obtain picture: ${error} app`)
      }, options)
    })
  }
}

export default upload
